<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div
        v-for="(item, index) in roleList"
        :key="item.roleId"
        :class="{ 'role-item': true, active: activeIndex === index }"
        @click="menuChange(index)"
      >
        <div class="role-info">
          <!-- svg-icon 是全局组件 -->
          <svg-icon :icon-class="activeIndex === index ? 'user-active' : 'user'" class="icon" />
          {{ item.roleName }}
        </div>
        <div class="more">
          <el-dropdown>
            <span class="el-dropdown-link">
              <svg-icon icon-class="more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- 在组件上@绑定的事件，识别为自定义事件
               需要组件内部绑定$emit('事件名')
               @事件名.native 修饰符（不推荐） 会自动将此自定事件绑定到组件内部最外层元素
                -->
              <!-- 普通元素身上@绑定为浏览器原生事件 -->
              <el-dropdown-item @click.native="toEdit(item.roleId)">编辑角色</el-dropdown-item>
              <el-dropdown-item @click.native="deleteRole(item.roleId)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="mini" @click="$router.push('/sys/addRole')"
        >添加角色</el-button
      >
    </div>
    <div class="right-wrapper">
      <el-tabs v-model="activeName">
        <el-tab-pane label="功能权限" name="permission">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="tree"
                :data="item.children"
                :props="defaultProps"
                :default-expand-all="true"
                check-strictly
                show-checkbox
                node-key="id"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员(${total})`" name="user">
          <div class="user-wrapper">
            <el-table :data="userList" style="width: 100%">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  getRoleListAPI,
  getTreeListAPI,
  getRoleDetailAPI,
  getRoleUserListAPI,
  delRoleUserAPI,
} from "@/api/system";
export default {
  name: "Role",
  data() {
    return {
      activeName: "permission",
      roleList: [],
      activeIndex: 0,
      treeList: [], // 权限列表
      defaultProps: {
        label: "title",
        disabled: () => true, // 禁用所有按钮
      },
      params: {
        page: 1,
        pageSize: 10,
      },
      total: 0,
      userList: [],
    };
  },
  async created() {
    await this.getRoleList();
    await this.getTreeList();
    this.menuChange(0);
  },
  methods: {
    // 删除角色
    deleteRole(id) {
      this.$confirm("您确定要删除该角色吗", "温馨提示")
        .then(async () => {
          await delRoleUserAPI(id);
          this.$message.success("删除成功");
          this.getRoleList();
        })
        .catch(() => {});
    },
    // 跳转到编辑角色
    toEdit(id) {
      // 注意 path传参 不用 params 参数（加不上）
      // this.$router.push({
      //  path（name）: '',
      //  query（params）: {
      //   参数:值
      // }})
      this.$router.push(`/sys/addRole?id=${id}`);
    },
    // 递归禁用所有按钮（可选）
    addDisabledProp(treeList) {
      treeList.forEach((item) => {
        item.disabled = true;
        if (item.children) {
          this.addDisabledProp(item.children);
        }
      });
    },
    // 获取权限列表
    async getTreeList() {
      this.treeList = (await getTreeListAPI()).data;
      // this.addDisabledProp(this.treeList);
    },
    // 获取角色列表
    async getRoleList() {
      this.roleList = (await getRoleListAPI()).data;
    },
    // 点击菜单切换事件/获取角色对应权限/成员信息
    async menuChange(outerIndex) {
      this.activeIndex = outerIndex;
      const roleId = this.roleList[outerIndex].roleId;
      const perms = (await getRoleDetailAPI(roleId)).data.perms;
      // 1. 组件中元素有多个相同的ref值， this.$refs.XX  找最后一个（相当于多词赋值）
      // 2. 如果拥有相同的ref值得元素是for循环出来的，那么会找到全部（是一个数组）
      this.$refs.tree.forEach((tree, innerIndex) => {
        tree.setCheckedKeys(perms[innerIndex]);
      });
      const {
        data: { rows, total },
      } = await getRoleUserListAPI(roleId, this.params);
      this.userList = rows;
      this.total = total;
    },
  },
};
</script>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;
  padding: 20px;
  ::v-deep .el-tree .el-checkbox.is-checked .el-checkbox__inner,
  ::v-deep .el-tree .el-checkbox.is-disabled.is-checked .el-checkbox__inner {
    background-color: #4caf50 !important;
    border-color: #4caf50 !important;
    box-shadow: none !important;
  }

  ::v-deep .el-tree .el-checkbox.is-checked .el-checkbox__inner::after,
  ::v-deep .el-tree .el-checkbox.is-disabled.is-checked .el-checkbox__inner::after {
    border-color: #fff !important;
  }
  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
      }
    }

    .more {
      display: flex;
      align-items: center;
    }
    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>
